#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>


#define MAX_ALLOCS  1000000

int main(int argc,char *argv[]){
    char *ptr[MAX_ALLOCS];
    int freeStep,freeMin,freeMax,blockSize,numAllocks,j;

    printf("\n");

    if (argc < 3|| strcmp(argv[1],"--help") == 0){
        printf("please input argvs\n");
        exit(-1);
    }

    if (sscanf(argv[1],"%d",&numAllocks) == 0) {
        printf("提取参数1失败\n");
        exit(-1);
    } 

    if (numAllocks > MAX_ALLOCS) {
        printf("input malloc size greater than max\n");
        exit(-1);
    }

    if (sscanf(argv[2],"%d",&blockSize) == 0) {
        printf("提取参数2失败\n");
        exit(-1);
    } 

    int fs,fmin,fmax;

    if (argc > 3) {
        if (sscanf(argv[3],"%d",&fs) == 0) {
            printf("提取参数3失败\n");
            exit(-1);
        }
    }

    if (argc > 4){
     if (sscanf(argv[4],"%d",&fmin) == 0) {
            printf("提取参数4失败\n");
            exit(-1);
        }
    }

    if (argc > 5) {
     if (sscanf(argv[5],"%d",&fmax) == 0) {
            printf("提取参数5失败\n");
            exit(-1);
        }
    }


    freeStep = (fs != 0) ? fs: 1;
    freeMin = (fmin != 0 ) ? fmin : 1;
    freeMax = (fmax != 0) ? fmax : numAllocks;

    if (freeMax > numAllocks){
        printf("free max greater than malloc free\n");
        exit(-1);
    }

    printf("Initial program break: %10p\n",sbrk(0));
    printf("Allocating  %d * %d bytes\n",numAllocks,blockSize);

    for(j = 0; j < numAllocks; j++){
        ptr[j] = malloc(blockSize);
        if (ptr[j] == NULL){
            printf("malloc error\n");
            exit(-1);
        }
    }

    printf("program break now is:  %10p\n",sbrk(0));

    printf("freeing blocks from %d to %d in steps of %d\n",freeMin,freeMax,freeStep);
    for (j = freeMin-1;j <freeMax;j += freeStep){
        free(ptr[j]);
    }

    printf("after free(),program break is now: %10p\n",sbrk(0)); // 这里free后不会改变program break的位置
    exit(0);
}